from rest_framework.response import Response
from rest_framework.views import APIView
from demo_app.ser import *

from demo_app.models import User


class LoginView(APIView):
    def get(self, request):
        return Response({'code': '0', 'msg': ''})

    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = User.objects.filter(username=username, password=password).first()
        if user:
            return Response({'code': '0', 'msg': '登录成功', 'uid': user.id, 'username': user.username})
        return Response({'code': '999', 'msg': '登录失败'})


class GoodsView(APIView):
    def get(self, request):
        ordering = request.GET.get('ordering')
        if ordering=='1':
            goods = Goods.objects.all().order_by('price')
        else:
            goods = Goods.objects.all().order_by('-price')
        ser = GoodsSerializer(goods, many=True)
        return Response({'code': '0', 'msg': '获取成功', 'data': ser.data})


class OrderView(APIView):
    def get(self, request):
        orders = Order.objects.all().order_by('-id')
        ser = OrderReadSerializer(orders, many=True)
        return Response({'code': '0', 'msg': '获取成功', 'data': ser.data})

    def post(self, request):
        ser = OrderWriteSerializer(data=request.data)
        if ser.is_valid():
            ser.save()
            ser.instance.goods.buy_num += 1
            ser.instance.goods.save()
            return Response({'code': '0', 'msg': '下单成功'})
        else:
            return Response({'code': '999', 'msg': '下单失败'})

    def put(self, request):
        order_id = request.data.get('oid')
        content = request.data.get('content')

        order = Order.objects.filter(id=order_id).first()

        order.comment = content
        order.is_comment = True
        order.save()

        order.goods.comment_num += 1
        order.goods.save()
        return Response({'code': '0', 'msg': '评论成功'})


class SearchView(APIView):
    def get(self, request):
        # 1. 搜索名字 2, 搜索价格
        goods_title = request.query_params.get('goods_title')
        max_price = request.query_params.get('max_price')
        min_price = request.query_params.get('min_price')

        if goods_title:
            goods_list = Goods.objects.filter(title__contains=goods_title)
        else:
            goods_list = Goods.objects.filter(price__gte=min_price, price__lte=max_price)

        if len(goods_list) > 0:
            ser = GoodsSerializer(goods_list, many=True)
            return Response({'code': '0', 'msg': '获取成功', 'data': ser.data})
        else:
            return Response({'code': '999', 'msg': '没搜到'})
